package com.zx.ishopping.services.impl;

import com.zx.ishopping.Constants.UpdateConstant;
import com.zx.ishopping.VO.OrderItemsVo;
import com.zx.ishopping.entity.Order;
import com.zx.ishopping.entity.OrderItem;
import com.zx.ishopping.entity.Products;
import com.zx.ishopping.exceptions.ProductException;
import com.zx.ishopping.mapper.OrderItemsMapper;
import com.zx.ishopping.mapper.OrderMapper;
import com.zx.ishopping.mapper.ProductMapper;
import com.zx.ishopping.services.OrderItemsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;

@Slf4j
@Service
public class OrderItemsServiceImpl implements OrderItemsService {

    
    @Autowired
    private OrderItemsMapper orderItemsMapper;
    
    @Autowired
    private ProductMapper productMapper;
    
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private CacheManager cacheManager;

    /**
     * 获取订单项列表
     * @param orderId
     * @return
     */
    @Override
    public List<OrderItemsVo> getOrderItemsList(Long orderId) {
        List<OrderItemsVo> orderItemsList = orderItemsMapper.getOrderItemsList(orderId);
        return orderItemsList;
    }

    /**
     * 添加订单项数量
     */
    @Transactional
    @Override
    public void addNum(Long id) {

        // 涉及商品库存的修改，所以需要清理缓存
        cacheManager.getCache("productList").clear();

        // 先根据id查询到订单项
        OrderItem orderItem = orderItemsMapper.getProduct(id);
        int num = orderItem.getQuantity() + 1; // 数量+1

        boolean success = false;

        for (int i = 0; i < 3; i++) { // 最多尝试3次
            // 重新查询商品，拿到最新库存和 version
            Products product = productMapper.getById(orderItem.getProductId());

            if (product.getStock() <= 0) {
                throw new ProductException(UpdateConstant.STOCK_IS_NULL);
            }

            // 修改订单项的数量和总价
            BigDecimal price = product.getPrice();
            BigDecimal totalPrice = price.multiply(new BigDecimal(num));
            orderItem.setQuantity(num);
            orderItem.setTotalPrice(totalPrice);
            orderItemsMapper.updateOrderItem(orderItem);

            // 扣减库存
            product.setStock(product.getStock() - 1);

            // === 乐观锁更新 ===
            int rows = productMapper.update(product);
            // 这里的 update SQL 必须是：where id=? and version=? → version=version+1

            if (rows > 0) {
                // 更新成功 → 修改订单总价
                Order order = orderMapper.getById(orderItem.getOrderId());
                BigDecimal totalAmount = order.getTotalAmount().add(price);
                order.setTotalAmount(totalAmount);
                orderMapper.updateOrder(order);

                success = true;
                break;
            }

            // 如果 rows == 0，说明 version 冲突，进入下一轮循环（重试）
        }

        if (!success) {
            throw new ProductException("库存更新失败，请稍后重试");
        }

        // 延迟双删，清理缓存
        CompletableFuture.runAsync(() -> {
            try {
                Thread.sleep(500);
            } catch (InterruptedException ignored) {}
            cacheManager.getCache("productList").clear();
        });
    }



    /**
     * 减少订单数量
     * @param id
     */
    @Transactional
    @Override
    public void reduceNum(Long id) {

        // 先清一次缓存（防止脏读）
        cacheManager.getCache("productList").clear();

        // 根据id获取订单项
        OrderItem orderItem = orderItemsMapper.getProduct(id);

        boolean success = false;

        for (int i = 0; i < 3; i++) { // 最多尝试3次
            // 每次循环都重新查最新商品和订单
            Products product = productMapper.getById(orderItem.getProductId());
            BigDecimal price = product.getPrice();
            Order order = orderMapper.getById(orderItem.getOrderId());

            if (orderItem.getQuantity() == 1) {
                // === 数量为1，直接删除订单项 ===
                orderItemsMapper.deleteOrderItems(id);

                // 修改库存 + 乐观锁更新
                product.setStock(product.getStock() + 1);
                int rows = productMapper.update(product);

                if (rows > 0) {
                    // 更新订单总价
                    order.setTotalAmount(order.getTotalAmount().subtract(price));
                    orderMapper.updateOrder(order);
                    success = true;
                    break;
                }
            } else {
                // === 数量大于1，减一 ===
                int num = orderItem.getQuantity() - 1;
                BigDecimal totalPrice = price.multiply(new BigDecimal(num));

                orderItem.setQuantity(num);
                orderItem.setTotalPrice(totalPrice);
                orderItemsMapper.updateOrderItem(orderItem);

                // 修改库存 + 乐观锁更新
                product.setStock(product.getStock() + 1);
                int rows = productMapper.update(product);

                if (rows > 0) {
                    // 更新订单总价
                    order.setTotalAmount(order.getTotalAmount().subtract(price));
                    orderMapper.updateOrder(order);
                    success = true;
                    break;
                }
            }

            // 如果 rows == 0，说明 version 不一致，进入下一轮循环
            orderItem = orderItemsMapper.getProduct(id); // 重新拿最新数据
        }

        if (!success) {
            throw new ProductException("库存更新失败，请稍后重试");
        }

        // 延迟双删
        CompletableFuture.runAsync(() -> {
            try {
                Thread.sleep(500);
            } catch (InterruptedException ignored) {}
            cacheManager.getCache("productList").clear();
        });
    }

    /**
     * 删除订单项
     * @param id
     */
    @Transactional
    @Override
    public void deleteOrderItem(Long id) {
        // 先清一次缓存（防止读到旧数据）
        cacheManager.getCache("productList").clear();

        // 查询该订单项
        OrderItem orderItem = orderItemsMapper.getProduct(id);
        if (orderItem == null) {
            throw new ProductException("订单项不存在");
        }

        boolean success = false;

        for (int i = 0; i < 3; i++) { // 最多尝试3次
            // 每次循环都重新查最新数据
            Order order = orderMapper.getById(orderItem.getOrderId());
            Products product = productMapper.getById(orderItem.getProductId());

            BigDecimal price = orderItem.getTotalPrice();

            // 修改订单金额
            order.setTotalAmount(order.getTotalAmount().subtract(price));
            orderMapper.updateOrder(order);

            // 回退库存
            product.setStock(product.getStock() + orderItem.getQuantity());
            int rows = productMapper.update(product); // 乐观锁更新

            if (rows > 0) {
                // 删除订单项
                orderItemsMapper.deleteOrderItems(id);
                success = true;
                break;
            }

            // 如果失败，重新获取最新 orderItem
            orderItem = orderItemsMapper.getProduct(id);
            if (orderItem == null) {
                // 已经被删掉了，直接退出
                success = true;
                break;
            }
        }

        if (!success) {
            throw new ProductException("删除订单失败，请稍后重试");
        }

        // 延迟双删
        CompletableFuture.runAsync(() -> {
            try {
                Thread.sleep(500);
            } catch (InterruptedException ignored) {}
            cacheManager.getCache("productList").clear();
        });
    }

}
